package com.ymtms.arrivalofgoods.aspect;

import com.google.gson.Gson;
import com.ymtms.arrivalofgoods.anotation.Syslog;
import com.ymtms.arrivalofgoods.bo.SyslogBO;
import com.ymtms.arrivalofgoods.service.impl.SyslogServiceImpl;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Aspect
@Component
public class SyslogAspect {
    @Autowired
    private SyslogServiceImpl syslogService;


    /**
     * Discription Todo使用注解方式定义切入点
     *
     * @return
     * @Param
     * @author Administrator
     * @date 2019/10/28 10:19
     **/
    @Pointcut("@annotation(com.ymtms.arrivalofgoods.anotation.Syslog)")
    public void logPointcut() {

    }

    //定义切入方法
    @Around("logPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long beginTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long time = System.currentTimeMillis() - beginTime;
        saveLog(joinPoint, time);
        return result;
    }
/**
*Discription Todo保存日志
*@Param
*@return
*@author Administrator
*@date 2019/10/28 10:46
**/
    private void saveLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SyslogBO syslog = new SyslogBO();
        syslog.setExcuTime(time);
        syslog.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        Syslog annotation = method.getAnnotation(Syslog.class);
        if (annotation != null) {
            syslog.setRemark(annotation.value());
        }
        syslog.setClassName(joinPoint.getTarget().getClass().getName());
        syslog.setMethodName(signature.getName());

        Object[] args = joinPoint.getArgs();
        List params = new ArrayList();
        for (Object arg : args) {
            params.add(new Gson().toJson(arg));

        }
        syslog.setParams(params.toString());
        syslogService.save(syslog);
    }


}
